package org.example.servlet;


import org.example.model.ResponseStatus;
import org.example.model.User;
import org.example.util.Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/logout")   //注销用户
public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");

        HttpSession session = req.getSession(false);
        if(session != null){
            User user = (User)session.getAttribute("user");  //如果session不为空取user信息
            if(user != null){
                //用户已经登录：删除session中保存的用户信息（起到注销用户或者退出登录效果）
                session.removeAttribute("user");
                //注销成功返回ok： false
                ResponseStatus response = new ResponseStatus();
                response.setOk(true);
                resp.getWriter().println(Util.serialize(response));
                return ;
            }
            //用户没有登录时候
            ResponseStatus response = new ResponseStatus();
            response.setReason("用户没有登录，不能访问！");
            resp.getWriter().println(Util.serialize(response));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
